package service.bingosearch;

import java.io.File;
import java.io.IOException;
import java.util.List;

import models.Offer;
import models.Request;
import models.Service;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

import com.google.gson.FieldNamingPolicy;

import play.db.jpa.GenericModel.JPAQuery;

public class IndexManager {

	private String pyhsicalRootPath = "Bingo/src/data/bingosearch";
	
	public Directory GetIndex(String modelName) throws IOException{
		File file = new File(pyhsicalRootPath + "/" + modelName + ".index");
		return FSDirectory.open(file);
	}
	
    public void BuildSearchIndexes() throws Exception, LockObtainFailedException, IOException{
    	BuildServiceIndex();
    }
    
    private void BuildServiceIndex() throws CorruptIndexException, LockObtainFailedException, IOException{
    	//Offers
    	JPAQuery query = Offer.all();
    	List<Offer> offers = query.fetch();
    	
     	//Requests
    	JPAQuery query2 = Request.all();
    	List<Request> requests = query2.fetch();
    	
    	Directory index = GetIndex("service");
    	IndexWriter writer = new IndexWriter(index, new StandardAnalyzer(Version.LUCENE_CURRENT), true, IndexWriter.MaxFieldLength.LIMITED);
    	
    	for (Offer offer : offers) {
    		AddServiceDocument(writer, offer);
    	}
    	for (Request request : requests) {
    		AddServiceDocument(writer, request);
    	}
    	
    	writer.close();
    }
    
    private void AddServiceDocument(IndexWriter writer, Service service) throws CorruptIndexException, IOException{
    	
        	Document doc = new Document();
        	doc.add(new Field("id",service.id.toString(), Field.Store.YES, Field.Index.ANALYZED));
        	doc.add(new Field("title",service.title , Field.Store.YES, Field.Index.ANALYZED));
        	doc.add(new Field("description", service.description, Field.Store.YES, Field.Index.ANALYZED));
        	doc.add(new Field("owner.fullname",service.owner.fullname,Field.Store.YES, Field.Index.ANALYZED));
        	doc.add(new Field("owner.id",service.owner.id.toString(),Field.Store.YES, Field.Index.ANALYZED));
        	doc.add(new Field("isoffer", (service instanceof Offer) ? "1" : "0" ,Field.Store.YES, Field.Index.ANALYZED));
        	
        	//doc.add(new Field("owner.fullname",offer.,Field.Store.YES, Field.Index.ANALYZED));
        	writer.addDocument(doc);
		
    }
	
}
